package com.pro01.backend.utils;

import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.BEncoder;
import com.turn.ttorrent.bcodec.BDecoder;

import java.io.*;
import java.net.InetAddress;
import java.util.Map;
import java.util.HashMap;

/*
public class TorrentModifier {

    public static File injectPeerIdIntoAnnounce(File originalTorrent, String peerId) throws IOException {
        InputStream in = new FileInputStream(originalTorrent);
        Map<String, BEValue> torrentData = BDecoder.bdecode(in).getMap();

        // 构建带参数的 announce URL
        String oldAnnounce = torrentData.get("announce").getString();
        String newAnnounce = oldAnnounce + "?peer_id=" + peerId;

        // 修改 announce 字段
        torrentData.put("announce", new BEValue(newAnnounce));

        // 生成新文件
        String fileName = originalTorrent.getName().replace(".torrent", "") + "_mod.torrent";
        File modifiedTorrent = new File(originalTorrent.getParent(), fileName);
        OutputStream out = new FileOutputStream(modifiedTorrent);
        BEncoder.bencode(torrentData, out);
        out.close();

        return modifiedTorrent;
    }
}
 */

public class TorrentModifier {

    public static File injectPeerIdIntoAnnounce(File originalTorrent, String peerId) throws IOException {
        try (InputStream in = new FileInputStream(originalTorrent)) {

            Map<String, BEValue> torrentData = BDecoder.bdecode(in).getMap();
            if (!torrentData.containsKey("announce")) {
                throw new IOException("无 announce 字段，无法修改 .torrent");
            }

            String oldAnnounce = torrentData.get("announce").getString("UTF-8");

            // 防止重复注入 peer_id 参数
            String newAnnounce;
            if (oldAnnounce.contains("?")) {
                newAnnounce = oldAnnounce + "&peer_id=" + peerId;
            } else {
                newAnnounce = oldAnnounce + "?peer_id=" + peerId;
            }

            // 替换 announce 字段
            Map<String, BEValue> modifiedData = new HashMap<>(torrentData);
            modifiedData.put("announce", new BEValue(newAnnounce));

            // 生成新 .torrent 文件
            String fileName = originalTorrent.getName().replace(".torrent", "") + "_mod.torrent";
            File modifiedTorrent = new File(originalTorrent.getParent(), fileName);

            try (OutputStream out = new FileOutputStream(modifiedTorrent)) {
                BEncoder.bencode(modifiedData, out);
            }

            return modifiedTorrent;
        }
    }

//    public static File injectPasskeyIntoAnnounce(File originalTorrent, String passkey) throws IOException {
//        try (InputStream in = new FileInputStream(originalTorrent)) {
//
//            Map<String, BEValue> torrentData = BDecoder.bdecode(in).getMap();
//            if (!torrentData.containsKey("announce")) {
//                throw new IOException("无 announce 字段，无法修改 .torrent");
//            }
//
//            // 原 announce 字符串
//            String oldAnnounce = torrentData.get("announce").getString("UTF-8");
//
//            // 提取原 tracker 的主机地址（忽略原来的参数）
//            String baseUrl = oldAnnounce.contains("?")
//                    ? oldAnnounce.substring(0, oldAnnounce.indexOf("?"))
//                    : oldAnnounce;
//
//            // 使用当前主机 IP 注入新的 tracker URL
//            InetAddress ip = InetAddress.getLocalHost();
//            String ipAddress = ip.getHostAddress();
//            String newAnnounce = "http://" + ipAddress + ":7070/announce?passkey=" + passkey;
//
//            // 替换 announce 字段
//            Map<String, BEValue> modifiedData = new HashMap<>(torrentData);
//            modifiedData.put("announce", new BEValue(newAnnounce));
//
//            // 生成新的 .torrent 文件
//            String fileName = originalTorrent.getName().replace(".torrent", "") + "_with_passkey.torrent";
//            File modifiedTorrent = new File(originalTorrent.getParent(), fileName);
//
//            try (OutputStream out = new FileOutputStream(modifiedTorrent)) {
//                BEncoder.bencode(modifiedData, out);
//            }
//
//            return modifiedTorrent;
//        }
//    }

    public static File injectPasskeyIntoAnnounce(File originalTorrent, String passkey) throws IOException {
        try (InputStream in = new FileInputStream(originalTorrent)) {

            Map<String, BEValue> torrentData = BDecoder.bdecode(in).getMap();
            if (!torrentData.containsKey("announce")) {
                throw new IOException("无 announce 字段，无法修改 .torrent");
            }

            InetAddress ip = InetAddress.getLocalHost();
            String ipAddress = ip.getHostAddress();
            String newAnnounce = "http://" + ipAddress + ":7070/announce?passkey=" + passkey;

            Map<String, BEValue> modifiedData = new HashMap<>(torrentData);
            modifiedData.put("announce", new BEValue(newAnnounce));

            // 自定义临时保存目录
            File tempDir = new File(System.getProperty("user.dir") + "/temp/torrents/");
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }

            File modifiedTorrent = new File(tempDir, originalTorrent.getName());
            try (OutputStream out = new FileOutputStream(modifiedTorrent)) {
                BEncoder.bencode(modifiedData, out);
            }

            return modifiedTorrent;
        }
    }


}

